package com.crayfish.banner.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Scroller;

/**
 * Created by lin on 2016/8/18.
 */
public class DragView extends View{

    private int lastX,lastY;

    private Scroller scroller;

    public DragView(Context context) {
        super(context);
    }

    public DragView(Context context, AttributeSet attrs) {
        super(context, attrs);
        scroller = new Scroller(context);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = (int)event.getX();
        int y = (int)event.getY();
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                lastX = x;
                lastY = y;
//                scrollBy(0,-100);
                break;
            case MotionEvent.ACTION_MOVE:
                //偏移量计算
                int offsetX = x - lastX;
                int offsetY = y - lastY;
                //随着手指的移动而移动
//                layout(getLeft()+offsetX,getTop()+offsetY,
//                        getRight()+offsetX,getBottom()+offsetY);
//                offsetLeftAndRight(offsetX);
//                offsetTopAndBottom(offsetY);
                //移动了父布局 所以看着是反向的
//                ((View)getParent()).scrollBy(offsetX,offsetY);
//                ((View)getParent()).scrollTo(offsetX,offsetY);
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
//                View view = (View)getParent();
//                scroller.startScroll(view.getScrollX(),view.getScrollY(),
//                        -view.getScrollX(),-view.getScrollY());
                scroller.startScroll(0,0,-100,0);
                invalidate();
                break;
        }
        return true;
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        //判断Scroller是否完成
        if(scroller.computeScrollOffset()){
            scrollTo(scroller.getCurrX(),scroller.getCurrY());
            //重绘触发computeScroll
            invalidate();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

    }
}
